﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Enemy : MonoBehaviour
{

    private Vector2 posiX = new Vector2(1f, 0);
    private Vector2 negtX = new Vector2(-1f, 0);
    private float Timer;
    private float Min = 0.5f;
    private float Max = 3.5f;
    private float tmp1;
    private float tmp2;
    private Rigidbody2D rigidbody;
    private BoxCollider2D collider;
    private int Direction = 1;
    private Vector2 targetPosition;
    private bool canMove = false;

    public Transform ziDan;//子弹



    // Use this for initialization
    void Start()
    {
        rigidbody = GetComponent<Rigidbody2D>();
        collider = GetComponent<BoxCollider2D>();
        targetPosition = transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        Timer += Time.deltaTime;
        if (Timer > 1)
        {
            tmp1 = Random.Range(Min, Max);
            tmp2 = Random.Range(Min, Max);
            Timer = 0;
        }

        //EnemyMoveAttack();
        if (canMove)
        {
            if (tmp1 < tmp2)
                rigidbody.MovePosition(rigidbody.position + posiX * Time.deltaTime);
            else
                rigidbody.MovePosition(rigidbody.position + negtX * Time.deltaTime);
        }



    }
    void EnemyMoveAttack()
    {
        collider.enabled = false;
        RaycastHit2D hitPx = Physics2D.Linecast(targetPosition, targetPosition + new Vector2(1, 0));
        RaycastHit2D hitNx = Physics2D.Linecast(targetPosition, targetPosition + new Vector2(-1, 0));
        RaycastHit2D hitY = Physics2D.Linecast(targetPosition, targetPosition + new Vector2(0, -1));
        collider.enabled = true;
        if (hitPx || hitNx)
        {
            Transform n = Instantiate(ziDan, transform.position, Quaternion.identity);
            n.GetComponent<Rigidbody2D>().AddForce(Vector2.right * 1000 * Direction);
        }
        if (hitY)
            canMove = true;
    }


    //public void OnCollisionEnter2D(Collision2D collision)
    //{
    //    if (collision.gameObject.tag == "Player")
    //    {
    //        ;
    //    }
    //}

}
